package ar.edu.uba.fi.jmit.sender.mock;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import ar.edu.uba.fi.jmit.integrationcommons.Event;
import ar.edu.uba.fi.jmit.integrationcommons.Message;

public class MockServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	private static Logger log = Logger.getLogger(MockServlet.class);
	private static int recivedMessages = 0;
	private int counter = 0;
	private List<Message> arrivedMessages;
	
	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		log = Logger.getLogger(this.getClass());
		arrivedMessages = new LinkedList<Message>();
		recivedMessages = 0;
	}
	

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		log.info("At doGet(): ");
		counter = 0;
		String action = req.getParameter("action");
		if(action == null) {
			this.showStatus(req, resp);
		}else if("restartQueue".equals(action)) {
			arrivedMessages.clear();
			recivedMessages = 0;
		}else if("obtainQueue".equals(action)) {
			ObjectOutputStream stream = new ObjectOutputStream(resp.getOutputStream());
			stream.writeObject(arrivedMessages);
		}
	}

	private void showStatus(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		resp.setContentType("text/html");
		post(resp, "At doGet() of MainClassHandler");
		InetAddress p = InetAddress.getLocalHost();
		post(resp, "Canonical host:" + p.getCanonicalHostName());
		post(resp, "Servlet recived  "+recivedMessages + " messages");
		if(!arrivedMessages.isEmpty()) {
			Message message = arrivedMessages.get(arrivedMessages.size() - 1);
			post(resp, "Last recived message: " + message.getHeader());
			post(resp, "Event: ");
			this.showEventData(req, resp, message);
		}
	}


	private void showEventData(HttpServletRequest req,
			HttpServletResponse resp, Message message) throws IOException {
		Event event = message.getBody();
		post(resp, "\tSource: " + event.getSource());
		post(resp, "\tPriority: " + event.getPriority());
		for(String key:event.getData().keySet()) {
			post(resp, "\t" + key + ":" + event.getData().get(key));
		}
		
	}


	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		log.info("Ar doPost() f MainClassHandler");
		InetAddress p = InetAddress.getLocalHost();
		log.info("Canonical host:" + p.getCanonicalHostName());
		log.info("Recived Message number: "+recivedMessages);
		log.info("Request content type: " + req.getContentType());
		log.info("Request content Length: " + req.getContentLength());
		log.info("Request Character Encoding: " + req.getCharacterEncoding());
		log.info("Input Stream Class: " + req.getInputStream().getClass());
		ObjectInputStream stream = new ObjectInputStream(req.getInputStream());
		Message message;
		try {
			message = (Message) stream.readObject();
			if(message == null) {
				log.info("No Object Readed");
			}else {
				log.info("Readed Message: " + message);
				log.info("Readed Message Header: " + message.getHeader());
				arrivedMessages.add(message);
				recivedMessages++;
			}
			
		} catch (ClassNotFoundException e) {
			log.error("Error");
		}
		resp.setContentType("text/plain");
		counter = 0;
	}
	
	private void post(HttpServletResponse resp, String txt) throws IOException {
		resp.getOutputStream().print(counter + ") " + txt + "</br>");
		log.info(counter + ")" + txt);
		counter++;
	}


}
